import xml.etree.ElementTree as ET
import os
import pickle
import numpy as np
from sklearn.metrics import average_precision_score


def box_iou_xyxy(b1, b2):
    bb1 = b1.copy()
    bb2 = b2.copy()
    w1 = b1[2] - b1[0]
    h1 = b1[3] - b1[1]
    w2 = b2[2] - b2[0]
    h2 = b2[3] - b2[1]
    bb1[2] = w1
    bb1[3] = h1
    bb2[2] = w2
    bb2[3] = h2
    return box_iou_xywh(bb1, bb2)


def box_iou_xywh(b1, b2):
    '''Return iou

    Parameters
    ----------
    b1: box1, xywh
    b2: box2, xywh

    Returns
    -------
    iou: double

    '''

    # Expand dim to apply broadcasting.

    left = max(b1[0], b2[0])
    top = max(b1[1], b2[1])
    b1_right = b1[0] + b1[2]
    b2_right = b2[0] + b2[2]

    b1_bottom = b1[1] + b1[3]
    b2_bottom = b2[1] + b2[3]

    b1_area = b1[2] * b1[3]
    b2_area = b2[2] * b2[3]
    right = min(b1_right, b2_right)
    bottom = min(b1_bottom, b2_bottom)

    x1 = max(bottom - top, 0.)
    x2 = max(right - left, 0.)
    intersect_area = x1 * x2
    iou = intersect_area * 1.0 / (b1_area + b2_area - intersect_area)

    return iou


def parse_iou(filename, inverse=False):
    all_boxes = dict()
    with open(filename) as fp:
        lines = fp.readlines()
        for line in lines:
            boxes = dict()
            val = line.split(' ')
            box_num = len(val)
            for i in range(1, box_num):
                box_val = val[i].split(',')
                c = int(box_val[4])
                box_vali = np.int32(box_val[:4])
                if inverse:
                    tmp = box_vali.copy()
                    box_vali = tmp[np.array([1, 0, 3, 2])]
                if not c in boxes.keys():
                    boxes[c] = [box_vali]
                else:
                    boxes[c].append(box_vali)
            all_boxes[val[0]] = boxes
    return all_boxes


def parse_rec(filename):
    """ Parse a PASCAL VOC xml file """
    tree = ET.parse(filename)
    objects = []
    for obj in tree.findall('object'):
        obj_struct = {}
        obj_struct['name'] = obj.find('name').text
        obj_struct['pose'] = obj.find('pose').text
        obj_struct['truncated'] = int(obj.find('truncated').text)
        obj_struct['difficult'] = int(obj.find('difficult').text)
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('xmin').text),
                              int(bbox.find('ymin').text),
                              int(bbox.find('xmax').text),
                              int(bbox.find('ymax').text)]
        objects.append(obj_struct)

    return objects


def voc_ap(rec, prec, use_07_metric=False):
    """ ap = voc_ap(rec, prec, [use_07_metric])
    Compute VOC AP given precision and recall.
    If use_07_metric is true, uses the
    VOC 07 11 point method (default:False).
    """
    if use_07_metric:
        # 11 point metric
        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                p = np.max(prec[rec >= t])
            ap = ap + p / 11.
    else:
        # correct AP calculation
        # first append sentinel values at the end
        mrec = np.concatenate(([0.], rec, [1.]))
        mpre = np.concatenate(([0.], prec, [0.]))

        # compute the precision envelope
        for i in range(mpre.size - 1, 0, -1):
            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])

        # to calculate area under PR curve, look for points
        # where X axis (recall) changes value
        i = np.where(mrec[1:] != mrec[:-1])[0]

        # and sum (\Delta recall) * prec
        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
    return ap


def voc_eval(detpath, annopath, ovthresh=0.5):
    """rec, prec, ap = voc_eval(detpath,
                                annopath,
                                imagesetfile,
                                classname,
                                [ovthresh],
                                [use_07_metric])

    Top level function that does the PASCAL VOC evaluation.

    detpath: Path to detections
        detpath.format(classname) should produce the detection results file.
    annopath: Path to annotations
        annopath.format(imagename) should be the xml annotations file.
    imagesetfile: Text file containing the list of images, one image per line.
    classname: Category name (duh)
    cachedir: Directory for caching the annotations
    [ovthresh]: Overlap threshold (default = 0.5)
    [use_07_metric]: Whether to use VOC07's 11 point AP computation
        (default False)
    """
    # assumes detections are in detpath.format(classname)
    # assumes annotations are in annopath.format(imagename)
    # assumes imagesetfile is a text file with each line an image name
    # cachedir caches the annotations in a pickle file

    # extract gt objects for this class
    class_recs = {}
    npos = 0
    for imagename in imagenames:
        R = [obj for obj in recs[imagename] if obj['name'] == classname]
        bbox = np.array([x['bbox'] for x in R])
        difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
        det = [False] * len(R)
        npos = npos + sum(~difficult)
        class_recs[imagename] = {'bbox': bbox,
                                 'difficult': difficult,
                                 'det': det}

    # read dets
    detfile = detpath.format(classname)
    with open(detfile, 'r') as f:
        lines = f.readlines()

    splitlines = [x.strip().split(' ') for x in lines]
    image_ids = [x[0] for x in splitlines]
    confidence = np.array([float(x[1]) for x in splitlines])
    BB = np.array([[float(z) for z in x[2:]] for x in splitlines])

    # sort by confidence
    sorted_ind = np.argsort(-confidence)
    sorted_scores = np.sort(-confidence)
    BB = BB[sorted_ind, :]
    image_ids = [image_ids[x] for x in sorted_ind]

    # go down dets and mark TPs and FPs
    nd = len(image_ids)
    tp = np.zeros(nd)
    fp = np.zeros(nd)
    for d in range(nd):
        R = class_recs[image_ids[d]]
        bb = BB[d, :].astype(float)
        ovmax = -np.inf
        BBGT = R['bbox'].astype(float)

        if BBGT.size > 0:
            # compute overlaps
            # intersection
            ixmin = np.maximum(BBGT[:, 0], bb[0])
            iymin = np.maximum(BBGT[:, 1], bb[1])
            ixmax = np.minimum(BBGT[:, 2], bb[2])
            iymax = np.minimum(BBGT[:, 3], bb[3])
            iw = np.maximum(ixmax - ixmin + 1., 0.)
            ih = np.maximum(iymax - iymin + 1., 0.)
            inters = iw * ih

            # union
            uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
                   (BBGT[:, 2] - BBGT[:, 0] + 1.) *
                   (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)

            overlaps = inters / uni
            ovmax = np.max(overlaps)
            jmax = np.argmax(overlaps)

        if ovmax > ovthresh:
            if not R['difficult'][jmax]:
                if not R['det'][jmax]:
                    tp[d] = 1.
                    R['det'][jmax] = 1
                else:
                    fp[d] = 1.
        else:
            fp[d] = 1.

    # compute precision recall
    fp = np.cumsum(fp)
    tp = np.cumsum(tp)
    rec = tp / float(npos)
    # avoid divide by zero in case the first detection matches a difficult
    # ground truth
    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
    ap = voc_ap(rec, prec, use_07_metric)

    return rec, prec, ap


def meanIOU(gtfile, resultfile, iou_threshold=0.5):
    result_boxes = parse_iou(resultfile, True)
    gt_boxes = parse_iou(gtfile)
    all_iou = []
    gt_match_all = []
    pred_match_all = []
    for image in result_boxes.keys():
        assert (image in gt_boxes.keys())
        gt_box = gt_boxes[image]
        result_box = result_boxes[image]
        num = 0
        iou_acc = 0

        for c in gt_box.keys():
            num += len(gt_box[c])
        match_count = 0
        count = 0
        gt_match = [0] * num
        pred_match = [0] * num
        for c in gt_box.keys():
            if c in result_box.keys():
                for gtb in gt_box[c]:
                    max_iou = 0
                    count += 1
                    for rb in result_box[c]:
                        max_iou = max(max_iou, box_iou_xyxy(gtb, rb))
                    if max_iou > iou_threshold:
                        match_count += 1
                        gt_match[count] = 1
                        pred_match[count] = 1
                    iou_acc += max_iou
            else:
                count += len(gt_box[c])
        iou = iou_acc / num
        all_iou.append(iou)
        [pred_match_all.append(item) for item in pred_match]
        [gt_match_all.append(item) for item in gt_match]
    pred_match_all = np.array(pred_match_all)
    gt_match_all = np.array(gt_match_all)
    precisions = np.cumsum(pred_match_all) / (np.arange(len(pred_match_all)) + 1)
    recalls = np.cumsum(pred_match_all).astype(np.float32) / len(gt_match_all)

    # Pad with start and end values to simplify the math
    precisions = np.concatenate([[0], precisions, [0]])
    recalls = np.concatenate([[0], recalls, [1]])

    for i in range(len(precisions) - 2, -1, -1):
        precisions[i] = np.maximum(precisions[i], precisions[i + 1])

        # Compute mean AP over recall range
    indices = np.where(recalls[:-1] != recalls[1:])[0] + 1
    mAP = np.sum((recalls[indices] - recalls[indices - 1]) *
                 precisions[indices])

    print(all_iou)
    print('mean IOU', sum(all_iou) / len(all_iou))
    print('precison', precisions)
    print('recall', recalls)
    print('mAP', mAP)


if __name__ == '__main__':
    gt_file = '../data/gt.txt'
    result_file = '../data/result.txt'

    meanIOU(gt_file, result_file)
